package com.huluobo.a2207douyindemo.videos;

import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.huluobo.a2207douyindemo.R;
import com.huluobo.a2207douyindemo.adapter.CommentAdapter;
import com.huluobo.a2207douyindemo.adapter.MultiVideoAdapter;
import com.huluobo.a2207douyindemo.databinding.FragmentVideosBinding;
import com.huluobo.a2207douyindemo.live.LiveActivity;
import com.huluobo.a2207douyindemo.login.LoginActivity;
import com.huluobo.base.bean.CommentBeanResult;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMFragment;
import com.huluobo.base.net.Const;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

public class VideosFragment extends BaseMVVMFragment<FragmentVideosBinding, VideoViewModel> {
    private MultiVideoAdapter videoAdapter;
    private CommentAdapter commentAdapter;

    private CommentAdapter childCommentAdapter;

    //当前展示的item的下标*****非常重要*****
    private int currentPosition = 0;
    //评论的下标,用于识别点击了哪个评论item的回复按钮
    private int commentPosition = 0;
    private StandardGSYVideoPlayer player;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_videos;
    }

    @Override
    protected void initData() {
        vm.getVideos(2, 10);
        vm.getVideosSuccess.observe(this, videoBeanResult -> {
            if (videoBeanResult.getCode() == 200) {
                videoAdapter.getData().clear();
                videoAdapter.getData().addAll(videoBeanResult.getData());
                videoAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(videoBeanResult.getMessage());
            }
        });

        vm.getVideosFailed.observe(this, s -> {
            Log.i("TagA", "获取视频列表失败:" + s);
        });

        vm.likeVideoSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setDianzan(1);
                videoAdapter.notifyDataSetChanged();
            }
        });

        vm.likeVideoFailed.observe(this, s -> {
            Log.i("TagA", "点赞失败:" + s);
        });

        vm.noLikeVideoSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setDianzan(0);
                videoAdapter.notifyDataSetChanged();
            }
        });

        vm.noLikeVideoFailed.observe(this, s -> {
            Log.i("TagA", "取消点赞失败:" + s);
        });

        vm.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setGuanzhu(1);
                videoAdapter.notifyDataSetChanged();
            }
        });

        vm.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        vm.getCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                commentAdapter.getData().clear();
                commentAdapter.getData().addAll(commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        vm.getCommentFailed.observe(this, s -> {
            Log.i("TagA", "获取评论列表失败:" + s);
        });

        vm.sendCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                //在评论列表数据源的第0位添加最新的数据
                commentAdapter.getData().addAll(0, commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();
                //获取输入框
                EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_videos_comment_et);
                assert editText != null;
                editText.setText("");

            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        vm.sendCommentFailed.observe(this, s -> {
            Log.i("TagA", "发送评论失败:" + s);
        });

        vm.responseCommentSuccess.observe(this, commentBeanResult -> {
            Log.i("TagA", "回复评论" + commentBeanResult.getData().get(0).getMsg());
        });

        vm.responseCommentFailed.observe(this, s -> {
            Log.i("TagA", "回复评论失败:" + s);
        });

    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        binding.videoRv.setLayoutManager(layoutManager);
        videoAdapter = new MultiVideoAdapter();
        binding.videoRv.setAdapter(videoAdapter);

        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(binding.videoRv);
        binding.videoRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                //当rv滚动后,获取当前展示的item的下标
                currentPosition = layoutManager.findFirstVisibleItemPosition();
                player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_videos_gsyPlayer);
                if (player != null) {
//                    player.startPlayLogic();
                }
            }
        });

        //添加item中的点击事件的id
        videoAdapter.addChildClickViewIds(R.id.item_videos_like_iv, R.id.item_videos_add_iv,
                R.id.item_videos_comment_iv, R.id.item_videos_close_iv, R.id.item_videos_comment_send_iv,
                R.id.item_videos_share_iv, R.id.item_videos_collect_iv, R.id.item_videos_live_cl,
                R.id.item_videos_full_cl);
        //设置item的点击监听事件
        videoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            VideoBeanResult.VideoBean videoBean = (VideoBeanResult.VideoBean) adapter.getData().get(position);
//            VideoBeanResult.VideoBean videoBean1 = videoAdapter.getData().get(position);
            String token = SPUtils.getInstance().getString(Const.PARAM_TOKEN);
            if (token.isEmpty()) {
                //没登录过
                Intent intent = new Intent(requireContext(), LoginActivity.class);
                startActivity(intent);
                return;
            }

            switch (view.getId()) {
                case R.id.item_videos_like_iv:
                    likeVideo(videoBean);
                    break;
                case R.id.item_videos_add_iv:
                    followAuth(videoBean);
                    break;
                case R.id.item_videos_comment_iv:
                    showComment(videoBean);
                    break;
                case R.id.item_videos_close_iv:
                    closeComment();
                    break;
                case R.id.item_videos_comment_send_iv:
                    sendComment(videoBean);
                    break;
                case R.id.item_videos_share_iv:
                    shareVideo(videoBean);
                    break;
                case R.id.item_videos_collect_iv:
                    collectVideo(videoBean);
                    break;
                case R.id.item_videos_live_cl:
                    toLive(videoBean);
                    break;
                case R.id.item_videos_full_cl:
                    fullScreen();
                    break;
            }
        });

    }

    private void fullScreen() {
        if (player != null) {
            player.setRotateViewAuto(true);//设置自动翻转屏幕
            player.startWindowFullscreen(requireContext(), false, false);//设置全屏,是否显示动作条,是否显示状态栏
            player.startPlayLogic();
        }
    }

    private void toLive(VideoBeanResult.VideoBean videoBean) {
        Intent intent = new Intent(requireContext(), LiveActivity.class);
        intent.putExtra("videoBean", videoBean);
        startActivity(intent);
    }

    //收藏视频
    private void collectVideo(VideoBeanResult.VideoBean videoBean) {
        AppDBUtils.getInstance().getVideoDao().insertVideoInfo(videoBean);
    }

    //分享
    private void shareVideo(VideoBeanResult.VideoBean videoBean) {
        //缩略图
        UMImage umImage = new UMImage(requireContext(), videoBean.getVideomainimg());
        umImage.compressStyle = UMImage.CompressStyle.SCALE;//压缩图片大小

        UMWeb web = new UMWeb(videoBean.getVideopath());//分享视频的路径
        web.setThumb(umImage);//缩略图
        web.setTitle(videoBean.getAuthname());//标题
        web.setDescription(videoBean.getCaption());//描述

        new ShareAction(requireActivity())
                .withMedia(web)
                .open();
    }

    //发送评论
    private void sendComment(VideoBeanResult.VideoBean videoBean) {
        //获取输入框
        EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et);
        assert editText != null;
        String msg = editText.getText().toString();
        if (msg.isEmpty()) {
            ToastUtils.showLong("评论内容不能为空");
        } else {
            vm.sendComment(msg, videoBean.getId());
        }
    }

    //关闭评论布局
    private void closeComment() {
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll);
        assert commentLayout != null;
        Animation animationOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out);
        animationOut.setDuration(500);
        commentLayout.startAnimation(animationOut);
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                commentLayout.setVisibility(View.GONE);
                binding.videoRv.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    //打开评论布局
    private void showComment(VideoBeanResult.VideoBean videoBean) {
        binding.videoRv.setIntercept(false);
        //获取评论布局
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll);
        assert commentLayout != null;
        commentLayout.setVisibility(View.VISIBLE);
        //加载动画
        Animation animationIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in);
        animationIn.setDuration(500);
        commentLayout.startAnimation(animationIn);

        //初始化评论布局
        RecyclerView commentRv = (RecyclerView) videoAdapter.getViewByPosition(currentPosition,
                R.id.item_videos_comment_rv);
        assert commentRv != null;
        commentRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        commentAdapter = new CommentAdapter();
        commentRv.setAdapter(commentAdapter);



        commentAdapter.addChildClickViewIds(R.id.item_comment_response_tv);
        commentAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            //初始化回复评论布局
            RecyclerView responseRv = (RecyclerView) commentAdapter.getViewByPosition(commentPosition,
                    R.id.item_comment_rv);
            assert responseRv != null;
            responseRv.setLayoutManager(new LinearLayoutManager(requireContext()));
            childCommentAdapter = new CommentAdapter();
            responseRv.setAdapter(childCommentAdapter);
            if (view.getId() == R.id.item_comment_response_tv) {
                ToastUtils.showLong("position:" + commentAdapter.getData().get(position).getRootid());
                vm.responseComment(videoBean.getId(), commentAdapter.getData().get(position).getId(), "回复的消息");
                CommentBeanResult.CommentBean commentBean = new CommentBeanResult.CommentBean();
                commentBean.setMsg("回复的消息");
                commentBean.setIcon(commentAdapter.getData().get(position).getIcon());
                commentBean.setUsername(commentAdapter.getData().get(position).getUsername());
                commentBean.setCreatetime(commentAdapter.getData().get(position).getCreatetime());
                childCommentAdapter.getData().add(commentBean);
                childCommentAdapter.notifyDataSetChanged();
            }
        });

        animationIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                vm.getComment(videoBean.getId());
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    //关注
    private void followAuth(VideoBeanResult.VideoBean videoBean) {
        vm.followAuth(videoBean.getAuthname());
    }

    //点赞视频和取消点赞视频
    private void likeVideo(VideoBeanResult.VideoBean videoBean) {
        if (videoBean.getDianzan() == 0) {
            //未点赞,触发点赞方法
            vm.likeVideo(videoBean.getId());
        } else {
            //一点赞,触发取消点赞方法
            vm.noLikeVideo(videoBean.getId());
        }
    }


    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }
}